import pygame
import sys

# 初始化pygame
pygame.init()

# 获取手柄数量
joystick_count = pygame.joystick.get_count()

if joystick_count == 0:
    print("未检测到手柄。请插入手柄后重新运行。")
    sys.exit()

# 获取第一个手柄
joystick = pygame.joystick.Joystick(0)
joystick.init()

# 设置屏幕
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("手柄输入显示")

# 设置字体
font = pygame.font.Font(None, 36)

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 清空屏幕
    screen.fill((255, 255, 255))

    # 获取手柄按键状态
    buttons = [joystick.get_button(i) for i in range(joystick.get_numbuttons())]

    # 显示按键状态
    for i, button_state in enumerate(buttons):
        button_text = font.render(f"Button {i}: {button_state}", True, (0, 0, 0))
        screen.blit(button_text, (10, 10 + i * 40))

    # 获取手柄轴状态
    axes = [joystick.get_axis(i) for i in range(joystick.get_numaxes())]

    # 显示轴状态
    for i, axis_value in enumerate(axes):
        axis_text = font.render(f"Axis {i}: {axis_value:.2f}", True, (0, 0, 0))
        screen.blit(axis_text, (140,20+i * 40))

    # 获取手柄十字方向键状态
    hat = joystick.get_hat(0)

    # 显示十字方向键状态
    hat_text = font.render(f"Hat: {hat}", True, (0, 0, 0))
    screen.blit(hat_text, (285, 30))

    # 刷新屏幕
    pygame.display.flip()
